//
//  PrivateMethod.m
//  MD5
//
//  Created by 金玉龙 on 15/11/17.
//  Copyright © 2015年 jinyulong. All rights reserved.
//

#import "PrivateMethod.h"
//MD5必备.h
#import <CommonCrypto/CommonDigest.h>
#import <LocalAuthentication/LocalAuthentication.h>
@implementation PrivateMethod
//16位MD5加密
+(NSString*)get16BitMD5StringFromString:(NSString*)string{
    const char *str = [string UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    return  string = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                    r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
}
//32位MD5加密
+(NSString*)get32BitMD5StringFromString:(NSString *)string{
    const char *str = [string UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    return  string = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                      r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15],r[16], r[17], r[18], r[19], r[20], r[21], r[22], r[23], r[24], r[25], r[26], r[27], r[28], r[29], r[30], r[31]];
}
//UUID
+(NSString *)getUUID{
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);
    return  [NSString stringWithFormat:@"%@", CFUUIDCreateString(NULL, uuid)];
}

#pragma mark 时间格式处理
+ (NSDate *)dateFromString:(NSString *)dateString
           withFormatStyle:(NSString *)formatStyle{
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatStyle];
    [dateformatter setTimeZone:[NSTimeZone defaultTimeZone]];
    NSDate *date = [dateformatter dateFromString:dateString];
    
    return date;
}

+ (NSDate *)getNotificationMatchDate:(NSString *)dateString addingTimeInterval:(NSTimeInterval)timeInterval
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *date = [[dateFormatter dateFromString:dateString] dateByAddingTimeInterval:timeInterval];
    return date;
}

+ (NSDate *)dateFromString:(NSString *)dateTimeStr
{
    //NSLog(@"dateFromString:%@",dateTimeStr);
    NSArray *array  = [dateTimeStr componentsSeparatedByString:@" "];
    NSArray *dateArr = [[array objectAtIndex:0] componentsSeparatedByString:@"-"];
    NSArray *timeArr = [[array objectAtIndex:1] componentsSeparatedByString:@":"];
    struct tm sourcedate;
    bzero((void*)&sourcedate,sizeof(sourcedate));
    sourcedate.tm_sec = ((NSString *)[timeArr objectAtIndex:2]).intValue;
    sourcedate.tm_min = ((NSString *)[timeArr objectAtIndex:1]).intValue;;
    sourcedate.tm_hour = ((NSString *)[timeArr objectAtIndex:0]).intValue;
    sourcedate.tm_mday = ((NSString *)[dateArr objectAtIndex:2]).intValue;;
    sourcedate.tm_mon = ((NSString *)[dateArr objectAtIndex:1]).intValue - 1;
    sourcedate.tm_year = ((NSString *)[dateArr objectAtIndex:0]).intValue - 1900;
    long timeInterval = mktime(&sourcedate);
    //NSLog(@"timeInterval:%ld",timeInterval);
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    //NSLog(@"date:%@",date);
    return date;
}


+ (NSString *)dateStringFromDate:(NSDate *)date
                 withFormatStyle:(NSString *)formatStyle{
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatStyle];
    NSString *dateStr=[dateformatter stringFromDate:date];
    
    return dateStr;
}

+ (NSString *)dateStringDescriptionByTimeOffset:(NSInteger)offset{
    
    NSTimeInterval second = offset*3600*24;
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:second];
    
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *comps = [calendar components:NSCalendarUnitYear fromDate:date];
    
    comps = [calendar components:NSCalendarUnitWeekday fromDate:date];
    NSInteger week = [comps weekday];
    
    NSString *weekday = nil;
    switch (week) {
        case 1:
            weekday = @"星期日";
            break;
        case 2:
            weekday = @"星期一";
            break;
        case 3:
            weekday = @"星期二";
            break;
        case 4:
            weekday = @"星期三";
            break;
        case 5:
            weekday = @"星期四";
            break;
        case 6:
            weekday = @"星期五";
            break;
        case 7:
            weekday = @"星期六";
            break;
            
        default:
            weekday = @"星期";
            break;
    }
    
    NSString *dateStr=[[self class] dateStringFromDate:date
                                          withFormatStyle:@"yyyy-MM-dd"];
    
    return [NSString stringWithFormat:@"%@ %@", dateStr, weekday];
    
}




//返回 小时:分钟
+ (NSString *)formatterHHhhDate:(NSString *)dateString{
    if (dateString.length >16) {
        return [dateString substringWithRange:NSMakeRange(11, 5)];
    }else if (dateString.length > 10){
        
        return [dateString substringWithRange:NSMakeRange(8, 2)];
    }
    return @"00:00";
}

+ (NSString *)formatterDateString:(NSString *)dateString
                    fromFormatter:(NSString *)fromeStyle
                      toFormatter:(NSString *)toStyle{
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:fromeStyle];
    [dateformatter setTimeZone:[NSTimeZone defaultTimeZone]];
    NSDate *date = [dateformatter dateFromString:dateString];
    
    dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:toStyle];
    [dateformatter setTimeZone:[NSTimeZone defaultTimeZone]];
    NSString *dateStr=[dateformatter stringFromDate:date];
    
    return dateStr;
    
}

+ (NSString *)matchShowTime:(NSString *)dataString
{
    if (dataString.length == 0) {
        return nil;
    }
    NSString *showTime = nil;
    NSDate *date = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMdd"];
    NSString *locationString=[dateformatter stringFromDate:date];
    NSString *localTime = [[self class] formatterDateString:dataString fromFormatter:@"yyyyMMddHHmmss" toFormatter:@"yyyyMMdd"];
    
    if ([locationString isEqualToString:localTime]){
        showTime = [[self class] formatterDateString:dataString fromFormatter:@"yyyyMMddHHmmss" toFormatter:@"今天 HH:mm"];
    }else{
        showTime = [[self class] formatterDateString:dataString fromFormatter:@"yyyyMMddHHmmss" toFormatter:@"M月d日 HH:mm"];
    }
    return showTime;
}

//*月*日
+ (NSString *)formatterMMDDDate:(NSString *)dateSting
{
    if (dateSting.length > 10) {
        return [NSString stringWithFormat:@"%@月%@日", [dateSting substringWithRange:NSMakeRange(5, 2)], [dateSting substringWithRange:NSMakeRange(8, 2)]];
    }
    return @"1月1日";
}

//*月*日 星期
+ (NSString *)formatterMMDDDateWithWeek:(NSString *)dateSting
                           fomaterStyle:(NSString *)fomaterStyle
{
    NSDate *date = [[self class] dateFromString:dateSting
                                   withFormatStyle:fomaterStyle];
    NSString *nowString = [[self class] dateStringFromDate:[NSDate date] withFormatStyle:@"MM-dd"];
    NSString *MMddString = [[self class] dateStringFromDate:date withFormatStyle:@"MM-dd"];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:NSCalendarUnitMonth fromDate:date];
    NSInteger month = [comps month];
    comps = [calendar components:NSCalendarUnitDay fromDate:date];
    NSInteger day = [comps day];
    comps = [calendar components:NSCalendarUnitWeekday fromDate:date];
    NSString *weekday = nil;
    switch ([comps weekday]) {
        case 1:
            weekday = @"星期日";
            break;
        case 2:
            weekday = @"星期一";
            break;
        case 3:
            weekday = @"星期二";
            break;
        case 4:
            weekday = @"星期三";
            break;
        case 5:
            weekday = @"星期四";
            break;
        case 6:
            weekday = @"星期五";
            break;
        case 7:
            weekday = @"星期六";
            break;
            
        default:
            weekday = @"星期";
    }
    
    if ([nowString isEqualToString:MMddString]) {
        return [NSString stringWithFormat:@"今天 %@", weekday];
    }
    
    return [NSString stringWithFormat:@"%@月%@日 %@", @(month), @(day), weekday];
}


+ (NSString *)totalTimeText:(CGFloat)totalTime{
    
    int time = (int)floor(totalTime);
    int hour = time/3600;
    int munites = time %3600 /60;
    int second = time%3600%60;
    
    return [NSString stringWithFormat:@"%02d:%02d:%02d", hour, munites, second];
}


#pragma mark - Autolayout coculation size

+ (void)setFittingFrameWithView:(UIView *)view{
    CGFloat height = [view systemLayoutSizeFittingSize:UILayoutFittingExpandedSize].height;
    CGRect frame = view.frame;
    
    frame.size.height = height;
    view.frame = frame;
}

#pragma mark -

+ (BOOL)checkAllIsBlankSpace:(NSString *)string{
    NSString *checkString = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (checkString.length > 0) {
        return NO;
    }
    return YES;
}

#pragma mark 图片处理
+ (UIImage *)imageFromColor:(UIColor *)color Width:(int)width Height:(int) height{
    CGRect rect = CGRectMake(0, 0,width,height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

+ (UIImage *)imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0f);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

+(UIColor *)colorWithHexColorString:(NSString *)hexColorString{
    if ([hexColorString length] <6){//长度不合法
        return [UIColor blackColor];
    }
    NSString *tempString=[hexColorString lowercaseString];
    if ([tempString hasPrefix:@"0x"]){//检查开头是0x
        tempString = [tempString substringFromIndex:2];
    }else if ([tempString hasPrefix:@"#"]){//检查开头是#
        tempString = [tempString substringFromIndex:1];
    }
    if ([tempString length] !=6){
        return [UIColor blackColor];
    }
    //分解三种颜色的值
    NSRange range;
    range.location =0;
    range.length =2;
    NSString *rString = [tempString substringWithRange:range];
    range.location =2;
    NSString *gString = [tempString substringWithRange:range];
    range.location =4;
    NSString *bString = [tempString substringWithRange:range];
    //取三种颜色值
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString]scanHexInt:&r];
    [[NSScanner scannerWithString:gString]scanHexInt:&g];
    [[NSScanner scannerWithString:bString]scanHexInt:&b];
    return [UIColor colorWithRed:((float) r /255.0f)
                           green:((float) g /255.0f)
                            blue:((float) b /255.0f)
                           alpha:1.0f];
}

//高斯模糊
+ (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur {
    //    if ((blur < 0.0f) || (blur > 1.0f)) {
    //        blur = 0.5f;
    //    }
    //
    //    int boxSize = (int)(blur * 100);
    //    boxSize -= (boxSize % 2) + 1;
    //
    //    CGImageRef img = image.CGImage;
    //
    //    vImage_Buffer inBuffer, outBuffer;
    //    vImage_Error error;
    //    void *pixelBuffer;
    //
    //    CGDataProviderRef inProvider = CGImageGetDataProvider(img);
    //    CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
    //
    //    inBuffer.width = CGImageGetWidth(img);
    //    inBuffer.height = CGImageGetHeight(img);
    //    inBuffer.rowBytes = CGImageGetBytesPerRow(img);
    //    inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
    //
    //    pixelBuffer = malloc(CGImageGetBytesPerRow(img) * CGImageGetHeight(img));
    //
    //    outBuffer.data = pixelBuffer;
    //    outBuffer.width = CGImageGetWidth(img);
    //    outBuffer.height = CGImageGetHeight(img);
    //    outBuffer.rowBytes = CGImageGetBytesPerRow(img);
    //
    //    error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL,
    //                                       0, 0, boxSize, boxSize, NULL,
    //                                       kvImageEdgeExtend);
    //
    //
    //    if (error) {
    //        NSLog(@"error from convolution %ld", error);
    //    }
    //
    //    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    //    CGContextRef ctx = CGBitmapContextCreate(
    //                                             outBuffer.data,
    //                                             outBuffer.width,
    //                                             outBuffer.height,
    //                                             8,
    //                                             outBuffer.rowBytes,
    //                                             colorSpace,
    //                                             CGImageGetBitmapInfo(image.CGImage));
    //
    //    CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
    //    UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
    //
    //    //clean up
    //    CGContextRelease(ctx);
    //    CGColorSpaceRelease(colorSpace);
    //
    //    free(pixelBuffer);
    //    CFRelease(inBitmapData);
    //
    //    CGColorSpaceRelease(colorSpace);
    //    CGImageRelease(imageRef);
    
    return nil;
}


+ (UIImage *)getScreenShot
{
    UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
    UIGraphicsBeginImageContext(screenWindow.frame.size);
    [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return viewImage;
}

//showOrHidden=yes 显示；showOrHidden=no，隐藏
+ (void)loadingAnimation:(BOOL)showOrHidden{
    
    UIImageView *iv = (UIImageView *)[[UIApplication sharedApplication].keyWindow viewWithTag:6949];
    
    if (showOrHidden && iv == nil) {
        iv = [[UIImageView alloc] init];
        iv.animationImages = @[];
        [[UIApplication sharedApplication].keyWindow addSubview:iv];
        
    }else if(!showOrHidden && iv){
        [iv removeFromSuperview];
    }
    
}

//static inline NSString *getMatchName(Match * match){
//
//}

+ (void)version {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    NSLog(@"Verson : %@", [NSString stringWithFormat:@"%@ build %@", version, build]);
}



+ (void)showLoading{
    
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
    iv.animationImages = @[[UIImage imageNamed:@"Loading001"],
                           [UIImage imageNamed:@"Loading002"],
                           [UIImage imageNamed:@"Loading003"],
                           [UIImage imageNamed:@"Loading004"],
                           [UIImage imageNamed:@"Loading005"],
                           [UIImage imageNamed:@"Loading006"],
                           [UIImage imageNamed:@"Loading007"],
                           [UIImage imageNamed:@"Loading008"],
                           [UIImage imageNamed:@"Loading009"],
                           [UIImage imageNamed:@"Loading010"],
                           [UIImage imageNamed:@"Loading011"],
                           [UIImage imageNamed:@"Loading012"],
                           [UIImage imageNamed:@"Loading013"],
                           [UIImage imageNamed:@"Loading014"],
                           [UIImage imageNamed:@"Loading015"],
                           [UIImage imageNamed:@"Loading016"]];
    [[UIApplication sharedApplication].keyWindow addSubview:iv];
    iv.animationDuration = 1.2;
    iv.tag = 1357896;
    iv.animationRepeatCount = 0;
    [iv startAnimating];
    
}

+ (void)hiddenLoading{
    
    UIImageView *iv = (UIImageView *)[[UIApplication sharedApplication].keyWindow viewWithTag:1357896];
    [iv stopAnimating];
    [iv removeFromSuperview];
    
}

+ (void)heartbeatView:(UIView *)view repeatCount:(NSInteger)repeat maxSize:(CGFloat)fMaxSize durationPerBeat:(CGFloat)fDurationPerBeat{
    if (view && (fDurationPerBeat > 0.1f))
    {
        CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
        
        CATransform3D scale1 = CATransform3DMakeScale(0.8, 0.8, 1);
        CATransform3D scale2 = CATransform3DMakeScale(fMaxSize, fMaxSize, 1);
        CATransform3D scale3 = CATransform3DMakeScale(fMaxSize - 0.3f, fMaxSize - 0.3f, 1);
        CATransform3D scale4 = CATransform3DMakeScale(1.0, 1.0, 1);
        
        NSArray *frameValues = [NSArray arrayWithObjects:
                                [NSValue valueWithCATransform3D:scale1],
                                [NSValue valueWithCATransform3D:scale2],
                                [NSValue valueWithCATransform3D:scale3],
                                [NSValue valueWithCATransform3D:scale4],
                                nil];
        
        [animation setValues:frameValues];
        
        NSArray *frameTimes = [NSArray arrayWithObjects:
                               [NSNumber numberWithFloat:0.05],
                               [NSNumber numberWithFloat:0.2],
                               [NSNumber numberWithFloat:0.6],
                               [NSNumber numberWithFloat:1.0],
                               nil];
        [animation setKeyTimes:frameTimes];
        
        animation.fillMode = kCAFillModeForwards;
        animation.duration = fDurationPerBeat;
        animation.repeatCount = repeat;
        
        [view.layer addAnimation:animation forKey:@"heartbeatView"];
    }else{}
}

+ (NSData *)dataWithImage:(UIImage *)image scaledToSize:(CGSize)newSize{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return UIImageJPEGRepresentation(newImage, 0.8);
}

+ (UIImage *)imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


+ (void)buttonSetTitleAndImageEges:(UIButton *)button{
    
    CGPoint buttonBoundsCenter = CGPointMake(CGRectGetMidX(button.bounds), CGRectGetMidY(button.bounds));
    
    CGPoint endImageViewCenter = CGPointMake(buttonBoundsCenter.x, CGRectGetMidY(button.imageView.bounds));
    CGPoint endTitleLabelCenter = CGPointMake(buttonBoundsCenter.x, CGRectGetHeight(button.bounds)-CGRectGetMidY(button.titleLabel.bounds));
    
    
    CGPoint startImageViewCenter = button.imageView.center;
    CGPoint startTitleLabelCenter = button.titleLabel.center;
    
    // 设置imageEdgeInsets
    
    CGFloat imageEdgeInsetsTop = endImageViewCenter.y - startImageViewCenter.y;
    CGFloat imageEdgeInsetsLeft = endImageViewCenter.x - startImageViewCenter.x;
    CGFloat imageEdgeInsetsBottom = -imageEdgeInsetsTop;
    CGFloat imageEdgeInsetsRight = -imageEdgeInsetsLeft;
    button.imageEdgeInsets = UIEdgeInsetsMake(imageEdgeInsetsTop, imageEdgeInsetsLeft, imageEdgeInsetsBottom, imageEdgeInsetsRight);
    
    // 设置titleEdgeInsets
    
    CGFloat titleEdgeInsetsTop = endTitleLabelCenter.y-startTitleLabelCenter.y;
    CGFloat titleEdgeInsetsLeft = endTitleLabelCenter.x - startTitleLabelCenter.x;
    CGFloat titleEdgeInsetsBottom = -titleEdgeInsetsTop;
    CGFloat titleEdgeInsetsRight = -titleEdgeInsetsLeft;
    button.titleEdgeInsets = UIEdgeInsetsMake(titleEdgeInsetsTop, titleEdgeInsetsLeft, titleEdgeInsetsBottom, titleEdgeInsetsRight);
    
    
    
    
}


+ (void)bundleLoadDylibWithPath:(NSString *)path{
    NSError *err = nil;
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    if ([bundle loadAndReturnError:&err]) {
        NSLog(@"bundle load framework success.");
    } else {
        NSLog(@"bundle load framework err:%@",err);
    }
}


+ (void)addRightBarButtonItemForSearchInController:(UIViewController *)vc
                                      withSelector:(SEL)selector{
    
    UIImage *sImage = [UIImage imageNamed:@"discover_ic_search_nor"];
    UIButton *rightBarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBarButton.frame= CGRectMake(0, 0, sImage.size.width, sImage.size.height);
    rightBarButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [rightBarButton setImage:[UIImage imageNamed:@"discover_ic_search_nor"] forState:UIControlStateNormal];
    [rightBarButton setImage:[UIImage imageNamed:@"discover_ic_search_press"] forState:UIControlStateHighlighted];
    [rightBarButton addTarget:vc action:selector forControlEvents:UIControlEventTouchUpInside];
    vc.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarButton];
}

+ (NSString *)regularImagePath:(NSString *)path andWithPathComponent:(NSString *)pathComponent{
    NSString *pathExtension = [path pathExtension];
    return [[[path stringByDeletingPathExtension] stringByAppendingPathComponent:pathComponent] stringByAppendingPathExtension:pathExtension];
}

+(NSString*)getCtime:(char*)arg{
    char outstr[200];
    time_t t;
    struct tm *tmp;
    
    t = time(NULL);
    tmp = localtime(&t);
    if (tmp == NULL)
    {
        NSLog(@"%@",@"localtime error");
        return @"";
    }
    
    if (strftime(outstr, sizeof(outstr), arg, tmp) == 0)
    {
        
        NSLog(@"%@",@"strftime returned 0");
        return @"";
    }
    return [NSString stringWithFormat:@"%s",outstr];
}

+(NSString*)getUnixStamp{
    return  [[self class] getCtime:"%s"];
}

+(CGSize)sizeForString:(NSString *)string font:(UIFont *)font size:(CGSize)size{
    CGSize newSize;
    CGRect newRect = [string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : font} context:nil];
    newSize        = newRect.size;
    return newSize;
}
//touchID
+ (void)authenticTouchIdSuccess:(voidBlock)authenticSuccess failure:(voidBlock)authenticFailure{
    LAContext *authenticContext = [LAContext new];
    LAPolicy policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics;
    BOOL canEvaluateAuthentic = [authenticContext canEvaluatePolicy:policy error:nil];
    if (canEvaluateAuthentic) {
        NSLog(@"Can Use TouchId");
        [authenticContext evaluatePolicy:policy localizedReason:@"验证指纹" reply:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                //验证成功
                if (authenticSuccess) {
                    authenticSuccess();
                }
            }else{
                //验证失败
                if (authenticFailure) {
                    authenticFailure();
                }
            }
        }];
    }else{
        NSLog(@"Can't Use TouchId");
    }
}
//获取某种颜色的image
+ (UIImage *)bgImageFromColors:(NSArray*)colors withFrame:(CGRect)frame{
    NSMutableArray *cgColors = [NSMutableArray array];
    for (UIColor *color in colors) {
        [cgColors addObject:(id)color.CGColor];
    }
    
    UIGraphicsBeginImageContextWithOptions(frame.size, YES, 1);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    
    CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)cgColors, NULL);
    
    CGPoint start = CGPointMake(0.0, frame.size.height);
    CGPoint end = CGPointMake(frame.size.width, 0.0);
    
    CGContextDrawLinearGradient(context, gradient, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    CGGradientRelease(gradient);
    CGContextRestoreGState(context);
    CGColorSpaceRelease(colorSpace);
    UIGraphicsEndImageContext();
    return image;
}

@end
